﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using UnityEngine.UI;

/// <summary>
/// 默认为Ready;
/// 点击开始并且鼠标松开,点击控制小球位置,StandBy;
/// 小球跌落过程中,Inprogress;
/// 水果跌落直至撞到其他小球或者墙壁时,回滚至StandBy;
/// 小球在发生碰撞后y坐标超出限制时游戏结束转到GameOver,然后出现UI展示玩家的得分
/// UI中有一个继续按钮，按下后转到Release状态，释放游戏资源，完毕后重载场景 
/// </summary>
public enum GameState
{
    Ready = 0,
    StandBy = 1,
    InProgress = 2,
    GameOver = 3,
    Release = 4,
}

public class GameManager : MonoBehaviour
{
    public GameObject startBtn;
    //public GameObject replayBtn;
    //public GameObject exitBtn;

    public GameObject[] CircleList;
    public GameObject bornPostion;
    public GameState gameState = GameState.Ready;
    public float combineScale = 0.5f;

    public Text UI_TotalScore;  //Text类需要用到using UnityEngine.UI;
    public Text UI_HighestScore;
    public Text UI_TotalScore2;

    public GameObject UI_Over;

    //音频源
    public AudioSource combineSource;
    public AudioSource hitSource;

    private int totalScore;     //总分数
    private int numCircle=0;      //创建的小球数量

    //静态的实例,可以在其他类中直接调用
    public static GameManager gmInstance;

    //该函数会在游戏对象启用之前调用一次，其优先度比Start()高
    private void Awake()
    {
        gmInstance = this;
    }

    public int max_Cmax_CreateSize = 4;
    // Start is called before the first frame update
    void Start()
    {
        //Debug.Log("hello");
        //初始化数据
        totalScore = 0;
        numCircle = 0;
        UI_TotalScore.text = "总分：" + totalScore.ToString();
        //加载最高分
        SetHighestScore();
        if (max_Cmax_CreateSize >= 9) max_Cmax_CreateSize = 9;
        if (max_Cmax_CreateSize < 1) max_Cmax_CreateSize = 1;
        //隐藏结束面板
        UI_Over.SetActive(false);
    }

    // Update is called once per frame
    void Update()
    {
        //Debug.Log(numCircle);
        if (gameState == GameState.GameOver)
        {

            //游戏结束了，展示总分，打开结束面板
            UI_TotalScore2.text = totalScore.ToString();
            UI_Over.SetActive(true);

        }
        else if (gameState == GameState.Release)
        {
            if (numCircle == 0)
            {
                ReLoadScene();
            }
        }
    }

    public void StartGame()
    {
        //游戏开始
        Debug.Log("游戏开始");
        startBtn.SetActive(false);
        gmInstance.gameState = GameState.StandBy;

        CreateNewCircle();
    }

    public void ReplayGame()
    {
        //重新开始游戏前要清理数据，设置游戏状态为Release
        if (gameState == GameState.GameOver)
        {
            gameState = GameState.Release;
            UI_Over.SetActive(false);
        }
        else
        {
            Debug.LogWarning("游戏状态不为GameOver的情况下触发了ReplyGame()函数");
        }
    }

    public void ExitGame()
    {
        Debug.Log("Quit Game");
        Application.Quit();
    }

    public void InvokeCreateNewCircle(float invokeTime)
    {
        //延迟一段时间后运行CreateCircle
        Invoke("CreateNewCircle", invokeTime);
    }

    //创建一个小球
    public void CreateNewCircle()
    {
        //小球数量+1
        numCircle++;

        int index = Random.Range(0, max_Cmax_CreateSize);
        if (CircleList.Length >= index && CircleList[index] != null)
        {
            GameObject CircleObj = CircleList[index];
            //创建小球
            var circle = Instantiate(CircleObj, bornPostion.transform.position, CircleObj.transform.rotation);
            circle.GetComponent<Circle>().circleState = CircleState.StandBy;
        }
        else
        {
            Debug.LogWarning("创建圆圈失败");
        }
    }

    /// <summary>
    /// 合成一个新的小球
    /// 合成后的小球size为cSize
    /// aPos,bPos为合并前的两个小球分别的位置
    /// </summary>
    public void CombineNewCircle(CircleSize cSize, Vector3 aPos, Vector3 bPos)
    {
        //小球数量+1
        numCircle++;

        Debug.Log("combine");
        Vector3 selfPos = (aPos + bPos) / 2;
        selfPos = aPos;
        int index = (int)cSize - 1;
        GameObject newCircleObj = CircleList[index];
        var newCircle = Instantiate(newCircleObj, selfPos, newCircleObj.transform.rotation);
        newCircle.GetComponent<Circle>().circleState = CircleState.Collision;
        newCircle.GetComponent<Rigidbody2D>().gravityScale = 2.0f;
        newCircle.transform.localScale *= combineScale;

        //增加分数
        AddScore(newCircle.GetComponent<Circle>().score);

        //播放音效
        combineSource.Play();
    }

    //增加分数,并更新UI
    public void AddScore(int score)
    {
        totalScore += score;
        UI_TotalScore.text = "总分："+totalScore.ToString();
    }

    //删除小球
    public void DelCIrcle(GameObject obj)
    {
        //小球数量-1
        numCircle--;
        Destroy(obj);
    }

    private void ReLoadScene()
    {
        int highestScore = PlayerPrefs.GetInt("HighestScore");
        if (totalScore > highestScore)
        {
            PlayerPrefs.SetInt("HighestScore", totalScore);
        }
        else
        {

        }
        SceneManager.LoadScene("Main");
    }

    private void SetHighestScore()
    {
        int score = PlayerPrefs.GetInt("HighestScore");
        UI_HighestScore.text = "历史最高分："+score.ToString();
    }
}
